<script setup>
import { onMounted, ref ,watch} from 'vue'
import { queryPageApi, addApi, queryInfoApi, updateApi, deleteApi } from '@/api/score'
import { ElMessage, ElMessageBox } from 'element-plus'
import { queryAllApi as queryAllStuApi } from '@/api/stu'
import { queryAllApi as queryAllSubApi } from '@/api/subject'

//所有的学生数据
let stus = ref([])
//加载所有的学生数据
const queryAllStu = async () => {
  let result = await queryAllStuApi()
  if (result.code) {
    stus.value = result.data
  }
}
//所有的学科数据
let subs = ref([])
//加载所有的学科数据
const queryAllSub = async () => {
  let result = await queryAllSubApi()
  if (result.code) {
    subs.value = result.data
  }
}

// 搜索表单对象
let searchScore = ref({ studentName: '' ,moduleName: '' })
// 列表数据
let tableData = ref([])

// 分页配置
const pagination = ref({ currentPage: 1, pageSize: 10, total: 0 })

// 初始化加载数据
onMounted(() => {
  queryPage()
  queryAllStu()
  queryAllSub()
})

// 分页查询
const queryPage = async () => {
  const result = await queryPageApi(
    searchScore.value.studentName,
    searchScore.value.moduleName,
    pagination.value.currentPage,
    pagination.value.pageSize
  )
  
  if (result.code) {
    tableData.value = result.data.rows
    pagination.value.total = result.data.total
  }
}

// 分页事件处理
const handleSizeChange = (pageSize) => {
  pagination.value.pageSize = pageSize
  queryPage()
}

const handleCurrentChange = (page) => {
  pagination.value.currentPage = page
  queryPage()
}

// 清空搜索
const clear = () => {
  searchScore.value = { studentName: '' ,moduleName: '' }
  queryPage()
}

// ----------- 新增/编辑 -----------
let dialogFormVisible = ref(false)
let formTitle = ref('')
let Score = ref({ moduleNo: '', studentNo: '', mark: '' ,attempt: '',attemptDate:'',id:'',moduleName:'',studentName:''})

// 表单校验规则
const ScoreFormRef = ref()
const rules = ref({
  name: [
    { required: true, message: '学科名称为必填项', trigger: 'blur' },
    { min: 2, max: 30, message: '名称长度为2-30个字符', trigger: 'blur' }
  ]
})

const clearScore = () => {
 Score.value = { moduleNo: '', studentNo: '', mark: '' ,attempt: '',attemptDate:'',id:'',moduleName:'',studentName:''}
}
// 打开新增弹窗
const addScore = () => {
  dialogFormVisible.value = true
  formTitle.value = '新增成绩信息'
  clearScore()
}

// 打开编辑弹窗
const updateScore = async (id) => {
  clearScore()
  const result = await queryInfoApi(id)
  if (result.code) {
    Score.value = result.data
    dialogFormVisible.value = true
    formTitle.value = '编辑成绩信息'
  }
}

// 保存数据
const save = async (ScoreForm) => {
  if(!ScoreForm)return
  ScoreForm.validate(async (valid) => {
    if (valid) {
      let api
      if (Score.value.id) {
        api = updateApi(Score.value)
      } else {
        api = addApi(Score.value)
      }
      let result = await api
      if (result.code) {
        ElMessage.success('操作成功')
        dialogFormVisible.value = false
        queryPage()
      }else{
        ElMessage.error(ref.msg)
      }
    }else{
      return false
    }
  })
}

// 删除学科
const delById = (id) => {
  ElMessageBox.confirm('确认删除该成绩信息吗？', '警告', { type: 'warning' })
    .then(async () => {
      const result = await deleteApi(id)
      if (result.code) {
        ElMessage.success('删除成功')
        queryPage()
      }
    })
    .catch(() => ElMessage.info('已取消'))
}
</script>

<template>
  <!-- 标题 -->
  <div id="title">成绩管理</div>
  <br>

  <!-- 搜索表单 -->
  <el-form :inline="true">
    <el-form-item label="学科名称">
      <el-input v-model="searchScore.moduleName" placeholder="请输入名称"/>
    </el-form-item>
    <el-form-item label="学生名称">
      <el-input v-model="searchScore.studentName" placeholder="请输入名称"/>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="queryPage">查询</el-button>
      <el-button @click="clear">重置</el-button>
    </el-form-item>
  </el-form>

  <!-- 操作按钮 -->
  <el-button type="success" @click="addScore">+ 新增成绩信息</el-button>
  <br><br>

  <!-- 数据表格 -->
  <el-table :data="tableData" border>
    <el-table-column type="index" label="序号" width="100"/>
    <el-table-column prop="studentName" label="学生姓名" width="160"/>
    <el-table-column prop="moduleName" label="学科名称" width="160"/>
    <el-table-column prop="mark" label="分数" width="160"/>
    <el-table-column prop="attempt" label="考试次数" width="160"/>
    <el-table-column prop="attemptDate" label="考试时间" width="160"/>
    <el-table-column label="操作" width="150">
      <template #default="{ row }">
        <el-button type="primary" size="small" @click="updateScore(row.id)">编辑</el-button>
        <el-button type="danger" size="small" @click="delById(row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <!-- 分页 -->
  <el-pagination
    v-model:current-page="pagination.currentPage"
    v-model:page-size="pagination.pageSize"
    :page-sizes="[5, 10, 20, 50]"
    layout="total, sizes, prev, pager, next"
    :total="pagination.total"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
  />

  <!-- 表单弹窗 -->
  <el-dialog v-model="dialogFormVisible" :title="formTitle" width="700px">
    <el-form ref="ScoreFormRef" :model="Score" :rules="rules">
      <el-form-item label="学生姓名" :label-width="labelWidth">
        <el-select v-model="Score.studentNo" placeholder="请选择学生" style="width: 100%;">
          <el-option v-for="stu in stus" :label="stu.name" :value="stu.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="学科" :label-width="labelWidth">
        <el-select v-model="Score.moduleNo" placeholder="请选择学科" style="width: 100%;">
          <el-option v-for="sub in subs" :label="sub.moduleName" :value="sub.moduleNo" />
        </el-select>
      </el-form-item>
      <el-form-item label="成绩" prop="mark" label-width="120px">
        <el-input v-model="Score.mark" placeholder="请输入成绩"/>
      </el-form-item>
      <el-form-item label="考试次数" prop="attempt" label-width="120px">
        <el-input v-model="Score.attempt" placeholder="请输入考试次数"/>
      </el-form-item>
      <el-form-item label="考试时间" prop="attemptDate" label-width="160px">
        <el-input v-model="Score.attemptDate" placeholder="请输入考试时间"/>
      </el-form-item>
      
    </el-form>
    <template #footer>
      <el-button @click="dialogFormVisible = false">取消</el-button>
      <el-button type="primary" @click="save(ScoreFormRef)">保存</el-button>
    </template>
  </el-dialog>
</template>

<style scoped>
#title {
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 20px;
}
</style>